package tsing.javase.util;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import java.util.Base64;

public class RSAStringEncryptor {

    private static final String RSA = "RSA";
    private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder();
    private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder();

    public static void main(String[] args) throws Exception {
        // 生成RSA密钥对
        KeyPair keyPair = generateKeyPair(RSA);

        // 获取公钥和私钥
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // 原始数据
        String originalText = "Hello, this is an RSA encryption test.";

        // 加密数据并转换为字符串
        String encryptedText = encryptToString(publicKey, originalText);

        // 将字符串解码回字节数组并解密
        String decryptedText = decryptFromBase64(privateKey, encryptedText);

        // 打印解密后的字符串
        System.out.println("Decrypted text: " + decryptedText);
    }

    public static KeyPair generateKeyPair(String algorithm) throws NoSuchAlgorithmException {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
        keyGen.initialize(2048);
        return keyGen.generateKeyPair();
    }

    public static String encryptToString(PublicKey publicKey, String text) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(text.getBytes());
        return BASE64_ENCODER.encodeToString(encryptedBytes);
    }

    public static String decryptFromBase64(PrivateKey privateKey, String base64EncodedData) throws Exception {
        byte[] decodedData = BASE64_DECODER.decode(base64EncodedData);
        Cipher cipher = Cipher.getInstance(RSA);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(decodedData);
        return new String(decryptedBytes);
    }


}
